package com.sgb.knowledgeshare.weight;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.ShareConfig;
import com.sgb.knowledgeshare.entity.ShareDictEntity3;
import com.sgb.knowledgeshare.entity.VideoCommentListEntity;
import com.sgb.knowledgeshare.view.adapter.CommentAdapter;
import com.swgk.core.base.model.entity.VideoBean;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SoftKeyBoardUtil;
import com.swgk.core.util.ThreadUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by：冯齐 on 2020/11/13 11:37
 * Description：  评论弹窗
 */
public class CommentDialog {

    private final TextView commentNumber, commentnodata, deleta, cancel;
    private final RelativeLayout commentDismiss, rlDeleteComment, sendCommentContent;
    private final EditText commentEditText;
    private final LRecyclerView lrecyclerview;
    private final View views;
    private final CommentAdapter commentAdapter;
    private final LinearLayout llCommentContent, llHeads;
    private int page;
    private boolean isreply = false;
    private int parseInt;
    private boolean openKeyboards;
    private boolean listSizeNum;

    public CommentDialog(Activity context, VideoBean videoData, String id, int type, int dataType) {
        page = 1;
        getCommentList(page, videoData, id, type,dataType);
        getCommentCount(videoData);
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(context, R.style.RoundCornerDialog);
        //2、设置布局
        View view = View.inflate(context, R.layout.comment_dialog, null);
        commentNumber = view.findViewById(R.id.comment_number);//标题
        commentDismiss = view.findViewById(R.id.comment_dismiss);//关闭
        commentEditText = view.findViewById(R.id.comment_editText);//输入框
        lrecyclerview = view.findViewById(R.id.lrecyclerview);//一级listview
        commentnodata = view.findViewById(R.id.comment_nodata);//暂时没有更多了
        rlDeleteComment = view.findViewById(R.id.rl_delete_comment);//删除布局
        llCommentContent = view.findViewById(R.id.ll_comment_content);//输入框总布局
        llHeads = view.findViewById(R.id.ll_heads);//弹窗处输入框外的布局id
        views = view.findViewById(R.id.views);//弹窗处输入框外的布局id
        deleta = view.findViewById(R.id.deleta);//删除
        cancel = view.findViewById(R.id.cancel);//取消
        sendCommentContent = view.findViewById(R.id.send_comment_content);//发送按钮的实现
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.ActionSheetDialogAnimation);
        //设置对话框大小
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int height = (1 * wm.getDefaultDisplay().getHeight()) / 3;
        views.getLayoutParams().height = height;
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog.show();
        commentDismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideKeyboard(context, commentEditText);
                onDialog.onhiedDialog();
                dialog.dismiss();
            }
        });
        views.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果软件盘是打开先关闭软件盘
                if (openKeyboards) {
                    openKeyboards = false;
                    hideKeyboard(context, commentEditText);
                } else {
                    if (rlDeleteComment.getVisibility() == View.VISIBLE) {
                        rlDeleteComment.setVisibility(View.GONE);
                    } else {
                        onDialog.onhiedDialog();
                        dialog.dismiss();
                    }
                }
            }
        });
        commentAdapter = new CommentAdapter(context, null, videoData.getCreateUser(), type, id);
        LRecyclerViewAdapter mLRecyclerViewAdapter = new LRecyclerViewAdapter(commentAdapter);
        lrecyclerview.setAdapter(mLRecyclerViewAdapter);
        lrecyclerview.setLayoutManager(new LinearLayoutManager(context));
        lrecyclerview.setPullRefreshEnabled(false);//禁止下拉刷新
        lrecyclerview.setLoadMoreEnabled(true);

        //加载更多
        lrecyclerview.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                getCommentList(page, videoData, id, type, dataType);
            }
        });

        commentAdapter.setCallback(new CommentAdapter.CommentCallback() {
            @Override
            public void onShowSoftKey() {
                isreply = true;
                openKeyboard(context, commentEditText);
            }

            @Override
            public void delete() {
                // 删除弹窗
                rlDeleteComment.setVisibility(View.VISIBLE);
            }

            @Override
            public void deleteSucceed() {
                onDialog.onhiedDialog();
                dialog.dismiss();
            }

            @Override
            public void onLoadSuccess() {
                isreply = false;
                commentEditText.clearFocus();
                commentEditText.setText("");
                getCommentCount(videoData);
                DialogHelper.dismissProgressDialog();
                if (commentAdapter.getDatas().size() > 0) {
                    commentnodata.setVisibility(View.GONE);
                }
            }
        });
        //删除
        deleta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentAdapter.deleteComment();
                //隐藏对话框
                rlDeleteComment.setVisibility(View.GONE);
            }
        });
        //取消
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rlDeleteComment.setVisibility(View.GONE);
            }
        });
        //发送
        sendCommentContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String contents = commentEditText.getText().toString().trim();
                if (!TextUtils.isEmpty(contents)) {
                    if (!isreply) {
                        isreply = false;
                        commentAdapter.setType(0);
                    }
                    commentAdapter.rely(contents, videoData.getVideoId(), videoData.getCreateUser());
                } else {
                    MToast.showToast(context, "请输入评论信息");
                }

            }
        });
        //评论框的输入监听
        commentEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 100) {
                    CharSequence sequence = s.toString().subSequence(0, 100);
                    commentEditText.setText(sequence);
                    commentEditText.setSelection(sequence.length());
                    MToast.showToast(context, "最多只能输入100字");
                }
            }
        });
        //软键盘监听事件
        SoftKeyBoardUtil.addOnSoftKeyBoardListener(context,
                new SoftKeyBoardUtil.OnSoftKeyBoardListener() {

                    @Override
                    public void keyBoardShow() {
                        //软键盘弹出，
                        openKeyboards = true;
                        if (commentnodata.getVisibility()==View.VISIBLE){
                            commentnodata.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void keyBoardHide() {
                        //软键盘关闭，
                        openKeyboards = false;
                        if (commentAdapter.getDatas().size()>0){
                            commentnodata.setVisibility(View.GONE);
                        }else {
                            commentnodata.setVisibility(View.VISIBLE);
                        }

                    }
                });
        Rect outRect = new Rect();
        context.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) llHeads.getLayoutParams();
        params.height = outRect.bottom - outRect.top;
        //输入框的点击事件

        commentEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                openKeyboards = true;
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    if (isreply) {
                        isreply = true;
                    } else {
                        String edit = commentEditText.getText().toString().trim();
                        if (TextUtils.isEmpty(edit)) {
                            isreply = false;
                        } else {
                            isreply = true;
                        }
                    }
                }
            }
        });
    }

    //获取视频总数
    private void getCommentCount(VideoBean videoData) {
        Map map = new HashMap();
        map.put("videoId", videoData.getVideoId());
        ShareConfig.getInstance().getApi().getCommentCount(map).enqueue(new Callback<BaseEntity<ShareDictEntity3>>() {
            @Override
            public void onResponse(Call<BaseEntity<ShareDictEntity3>> call, Response<BaseEntity<ShareDictEntity3>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(ShareConfig.RESPONSE_OK)) {
                    parseInt = Integer.parseInt(response.body().getData().getParam());
                    if (parseInt > 0) {
                        commentNumber.setText(parseInt + "条评论");
                    } else {
                        commentNumber.setText(0 + "条评论");
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ShareDictEntity3>> call, Throwable t) {
            }
        });
    }

    //输入框获取焦点、拉起软键盘
    private void openKeyboard(Activity context, EditText commentEditText) {
        commentEditText.requestFocus();
        ThreadUtils.runOnSubThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
            }
        });
    }

    //隐藏软键盘
    public static void hideKeyboard(Activity context, EditText commentEditText) {
        ThreadUtils.runOnSubThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(commentEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });
    }

    //获取评论列表
    private void getCommentList(int page, VideoBean videoData, String id, int type, int datatype) {
        Map map = new HashMap();
        map.put("videoId", videoData.getVideoId());
        map.put("pageNum", page);
        map.put("pageSize", 10);
        map.put("orderBy", 0);
        // map.put("type", datatype);
        map.put("id", id);
        ShareConfig.getInstance().getApi().apiGetVideoCommentList(map).enqueue(new Callback<BaseEntity<VideoCommentListEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<VideoCommentListEntity>> call, Response<BaseEntity<VideoCommentListEntity>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(ShareConfig.RESPONSE_OK)) {
                    lrecyclerview.refreshComplete(page);
                    List<VideoCommentListEntity.RecordsBeanX> records = response.body().getData().getRecords();
                    if (records == null)return;
                    if (page > 1) {
                        if (records.size() > 0) {
                           // isVideoList = records.size()>=10;
                            commentAdapter.setVisibleMoreText(records.size() < 10);
                            for (VideoCommentListEntity.RecordsBeanX bean : records) {
                                bean.setOneComment(false);
                            }
                            commentAdapter.addDatas(response.body().getData().getRecords());
                        } else {
                            commentAdapter.setVisibleMoreText(true);
                        //    isVideoList= false;
                        }
                    } else {
                        if (records.size() > 0) {
                            for (int i = 0; i < records.size(); i++) {
                                if (i == 0) {
                                    if (type == 2) {
                                        records.get(i).setOneComment(true);
                                    } else {
                                        records.get(i).setOneComment(false);
                                    }
                                } else {
                                    records.get(i).setOneComment(false);
                                }
                            }
                            //isVideoList = records.size()>=10;
                            commentAdapter.setVisibleMoreText(records.size() < 10);
                            commentAdapter.setDatas(response.body().getData().getRecords());
                        } else {
                            commentAdapter.setVisibleMoreText(false);
                            commentAdapter.setDatas(null);
                            commentnodata.setVisibility(View.VISIBLE);
                           // isVideoList= false;
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<VideoCommentListEntity>> call, Throwable t) {

            }
        });
    }

    private HiedDialog onDialog;

    public void setonDialog(HiedDialog onDialog) {
        this.onDialog = onDialog;
    }

    public interface HiedDialog {
        void onhiedDialog();
    }


}
